﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

// API de windows 7.
using Microsoft.WindowsAPICodePack.Dialogs;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Taskbar;
using Microsoft.WindowsAPICodePack;

using System.Media;
using System.Windows.Interop;


using System.IO;
using System.Reflection;
using WODXMPPCOMLib;


using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections;

namespace Emessenger
{
    /// <summary>
    /// Interaction logic for ContactListe.xaml
    /// </summary>
    public partial class ContactListe : Window
    {

        //ThumbnailToolbarButton : les bouttons qui seron ajouter a la "taskBare de windows 7"
        private ThumbnailToolbarButton EspritLink;
        private ThumbnailToolbarButton moodleLink;
        private ThumbnailToolbarButton Vide;
        private ThumbnailToolbarButton Esprit2;

        private TaskbarManager windowsTaskbar = TaskbarManager.Instance;

        string exchangeFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Dossier E-Messenger Exchange";


        //private string JID;
        Boolean SendFile = false;
        Boolean ReciveFile = false;

        SoundPlayer soundNotification = new SoundPlayer(@"c:/windows/media/tada.wav");
        private WODXMPPCOMLib.wodXMPPComClass wodXMPP1;

        public ContactListe(WODXMPPCOMLib.wodXMPPComClass wodXMPP)
        {
            InitializeComponent();
        
            wodXMPP1 = wodXMPP;
            wodXMPP1.ContactList += new WODXMPPCOMLib._IwodXMPPComEvents_ContactListEventHandler(wodXMPP1_ContactList);
            wodXMPP1.ContactStatusChange += new WODXMPPCOMLib._IwodXMPPComEvents_ContactStatusChangeEventHandler(wodXMPP1_ContactStatusChange);
            
            wodXMPP1.IncomingMessage += new WODXMPPCOMLib._IwodXMPPComEvents_IncomingMessageEventHandler(wodXMPP1_IncomingMessage);

            // File transfer
            //wodXMPP1.FileTransferStart += new WODXMPPCOMLib._IwodXMPPComEvents_FileTransferStartEventHandler(wodXMPP1_FileTransferStart);
           // wodXMPP1.FileTransferProgress += new WODXMPPCOMLib._IwodXMPPComEvents_FileTransferProgressEventHandler(wodXMPP1_FileTransferProgress);
           // wodXMPP1.FileTransferEnd +=new WODXMPPCOMLib._IwodXMPPComEvents_FileTransferEndEventHandler(wodXMPP1_FileTransferEnd);

            //wodXMPP1.VCardDetails += new _IwodXMPPComEvents_VCardDetailsEventHandler(wodXMPP1_VCardDetails);
            //wodXMPP1.ContactAuthRequest += new WODXMPPCOMLib._IwodXMPPComEvents_ContactAuthRequestEventHandler(wodXMPP1_ContactAuthRequest);
            wodXMPP1.Disconnected+=new _IwodXMPPComEvents_DisconnectedEventHandler(wodXMPP1_Disconnected);
            


            // Taskbar
            DataContext = this;
            this.Loaded += new RoutedEventHandler(Taskbar);
            
        }
       
        void wodXMPP1_FileTransferStart(WODXMPPCOMLib.XMPPContact Contact, WODXMPPCOMLib.XMPPFile File, ref WODXMPPCOMLib.XMPPActionsEnum Action)
        {
            
            //MessageBox.Show(exchangeFolder );
            if (SendFile == true)
            {
                Action = WODXMPPCOMLib.XMPPActionsEnum.Allow;
                SendFile = false;
            }
            else
            {

                soundNotification.Play(); // alerte sonnore :p
                if (MessageBox.Show("Contact: " 
                    + Contact.JID 
                    + "\r\nNom du fichier: " 
                    + File.Name + "\r\nTaille du fichier: " 
                    + File.Size + " bytes", Contact.Nick 
                    + " vous envoie un fichier.", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    //System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                    // 
                    //sfd.InitialDirectory = exchangeFolder;
                    //sfd.FileName = File.Name;
                    //if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)


                    //créer le dossier si il n'existe pas 
                    /*
                    if (Directory.Exists(exchangeFolder)==false) 
                    {
                        System.Diagnostics.Process.Start(exchangeFolder);
                    }*/

                    if (Directory.Exists(exchangeFolder) == false)
                    {
                        Directory.CreateDirectory(exchangeFolder);
                    }

                    Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

                    sfd.InitialDirectory = exchangeFolder;
                    sfd.FileName = File.Name;

                    if (sfd.ShowDialog() == true)
                    {
                        Action = WODXMPPCOMLib.XMPPActionsEnum.Allow;
                    }
                    else
                    {
                        Action = WODXMPPCOMLib.XMPPActionsEnum.Deny;
                    }
                    
                }
            }
        }

        


        void wodXMPP1_FileTransferProgress(WODXMPPCOMLib.XMPPContact Contact, WODXMPPCOMLib.XMPPFile File, int Position)
        {
            //MessageBox.Show("  " + Position / File.Size);
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
            TaskbarManager.Instance.SetProgressValue(Position, File.Size);


            progressBar1.Visibility = Visibility.Visible;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = File.Size;

            //label1.Content = Position;
            progressBar1.Value = Position;
            //Console.WriteLine(Position + " / " + File.Size);
            
        }

        void wodXMPP1_FileTransferEnd(WODXMPPCOMLib.XMPPContact Contact, WODXMPPCOMLib.XMPPFile File, int ErrorCode, string ErrorText)
        {
            if (ErrorCode != 0)
            {
                WarningBox warningBox = new WarningBox();
                warningBox.Owner = Window.GetWindow(this);
                warningBox.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                warningBox.text.Text = "FileTransfer Error: " + ErrorText;
                warningBox.ShowDialog();
                //MessageBox.Show("FileTransfer Error: " + ErrorText);
                //SendFile = false;
            }
            
            progressBar1.Visibility = Visibility.Hidden;
            //SendFile = false;
        }

        /// <summary>
        /// ////////////
        /// </summary>
        /// <param name="Contact"></param>
        /// <param name="ChatRoom"></param>
        /// <param name="Message"></param>

        int notf = 0;
        void wodXMPP1_IncomingMessage(WODXMPPCOMLib.XMPPContact Contact, WODXMPPCOMLib.XMPPChatRoom ChatRoom, WODXMPPCOMLib.XMPPMessage Message)
        {
            
            string[] nom = Contact.JID.Split(("@").ToCharArray());// Cherche le caractére @ est divise la phrase dans le tableau
            if (nom[0] == "")
            {
				notf++;
                //MessageBox.Show("notification  "+notf);
                Notif.Visibility = Visibility.Visible;
				notifCount.Content=notf;
				notifCount.Visibility = Visibility.Visible;
                Notification notif = new Notification();
                notif.message.Text = Message.Text ;
                notif.Show();
            }
            else
            fentre_de_chat(Contact.JID);
        }

        /// <summary>
        ///  cette methode affiche la liste de contacte
        ///  this method show the contact list
        /// </summary>
        void wodXMPP1_ContactList()
        {
            listBox1.Items.Clear();

            foreach (WODXMPPCOMLib.XMPPContact cnt in wodXMPP1.Contacts)
            {
                listBox1.Items.Add(cnt.JID + " (" + cnt.StatusText + ")");
            }
        }
        // 

        void wodXMPP1_ContactStatusChange(WODXMPPCOMLib.XMPPContact Contact, WODXMPPCOMLib.XMPPChatRoom ChatRoom, WODXMPPCOMLib.StatusEnum NewStatus, WODXMPPCOMLib.StatusEnum OldStatus)
        {
            String jid = Contact.JID;

            string[] jidparts = jid.Split('/');
            if (jidparts.Length > 1)
                jid = jidparts[0];

            int i;
            for (i = 0; i < listBox1.Items.Count; i++)
            {
                string line = listBox1.Items[i].ToString();
                string[] lines = line.Split((" ").ToCharArray());
                if (lines[0] == jid)
                {
                    listBox1.Items[i] = jid + " (" + Contact.StatusText + ")";
                }
            }
            listBox1.Items.Refresh(); // correction du probleme lié au changement de statut d'un contact (le nom du contact est toujours selectionné) 
        }


        
        private void choisirContact(object sender, MouseButtonEventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                /* ne rien faire si l'utilisateur ne selectionne rien*/
                /* do no think if user have no selected a contact */
            }
            else
            {
                string line = listBox1.SelectedItem.ToString();
                string[] lines = line.Split((" ").ToCharArray());
                fentre_de_chat(lines[0]);
            }
        }




        /// <Cette methode elle teste l'existance de la fenetre >
        /// 
        /// </summary>
        /// <param name="jid"></param>
        /// <returns>
        ///  si elle existe elle retourne la meme instance 
        ///  si non elle cree une nouvelle instance 
        /// </returns>



        private Chat fentre_de_chat(string jid)
        {
            string[] nom = jid.Split(("@").ToCharArray());// Cherche le caractére @ est divise la phrase dans le tableau
            
                Chat win2 = new Chat(jid, wodXMPP1);
                Boolean window_exists = false;
                int i;
                if (Application.Current.Windows.Count > 1)
                {
                    //MessageBox.Show("" + nom[0] + Application.Current.Windows.Count); //Test du numero et du Titre des fenetre ouverte
                    for (i = 1; i < Application.Current.Windows.Count; i++) // compter le nembre de fentre deja ouverte
                    {
                        if (Application.Current.Windows[i].Title == nom[0])
                        {
                            window_exists = true;
                            win2 = (Chat)Application.Current.Windows[i];
                            break;
                        }
                    }
                }
                if (window_exists != true)
                {
                    win2.textBox2.Text = jid;
                    win2.Title = nom[0];
                    win2.Show();
                    win2.textBox1.Focus();
                    win2.Focus();
                }
                return win2;
        }




        
        

        
        

        private void friend_add(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            AjouterAmi _ajouterAmi = new AjouterAmi(wodXMPP1);
            _ajouterAmi.Show();
        }

        private void ChatRoom_connect(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ChatRoom _chatRoom = new ChatRoom(wodXMPP1);
            _chatRoom.Show();
        }

        /*
        private void Notes(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }
        */

        /// <summary>
        /// Cette methode permet a l'utilisateur de changer sont statut
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       

        private void changer_statut(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex > 0)
            {
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                        {
                            wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.Online, null);
                            //MessageBox.Show("on line");
                        }
                        break;
                    case 1:
                        {
                            wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.Chat, null);
                            //MessageBox.Show("Free to chat");
                        }
                        break;
                    case 2:
                        {
                            wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.Away, null);
                            //MessageBox.Show("Away");
                        }
                        break;
                    case 3:
                        {
                            wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.ExtendedAway, null);
                            //MessageBox.Show("Extended Away");
                        }
                        break;
                    case 4:
                        {
                            wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.DoNotDisturb, null);
                            //MessageBox.Show("Do Not Disturb");
                        }
                        break;
                    case 5:
                        {
                            wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.Invisible, null);
                            //MessageBox.Show("Invisible");
                        }
                        break;
                    //case 7:
                    //    wodXMPP1.Disconnect();
                    //    break;
                }
            }
            //SetStatus();
        }


        private void ContextMenuClick(object sender, EventArgs e)
        {
            string line = listBox1.SelectedItem.ToString();
            string[] lines = line.Split((" ").ToCharArray());

            WODXMPPCOMLib.XMPPContact cnt;
            cnt = wodXMPP1.Contacts.Add(lines[0]);
            
            cnt.Unsubscribe();
            wodXMPP1.Contacts.Remove(cnt);

        }

        private void ouvrir_dossier(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (Directory.Exists(exchangeFolder) == false)
            {
                Directory.CreateDirectory(exchangeFolder);
            }
            System.Diagnostics.Process.Start(exchangeFolder);
        }


        //////////////////////////////////////////
        /////// Integration dans windows 7 ///////
        //////////////////////////////////////////

        void Taskbar(object sender, RoutedEventArgs e)
        {
            EspritLink = new ThumbnailToolbarButton(Properties.Resources.esprit, "Go To ESPRIT OnLine");
            EspritLink.Click += goToEsprit;

            moodleLink = new ThumbnailToolbarButton(Properties.Resources.moodle, "Go To moodle");
            moodleLink.Click += goToMoodle;


            Vide = new ThumbnailToolbarButton(Properties.Resources.moodle, null);
            Vide.Visible = false;


            Esprit2 = new ThumbnailToolbarButton(Properties.Resources.esprit2, "Go To ESPRIT");
            Esprit2.Click += goToEsprit_ens;
            

            //Creation de la jumpList "Liste personnaliser des taches"///////////////////////////////////////////////////////////////////
            TaskbarManager.Instance.ThumbnailToolbars.AddButtons(new WindowInteropHelper(this).Handle, EspritLink, moodleLink,Vide,Esprit2);
            JumpList jumplist = JumpList.CreateJumpList();
            
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            
            //Appropo des développeurs///////////////////////////////////////////////////////////////////////////////////////////////////
            JumpListCustomCategory catActions = new JumpListCustomCategory("Realized by :");
            catActions.AddJumpListItems(
                
                new JumpListLink("http://www.facebook.com/grindi", "Grindi Nizar"),
                new JumpListLink("http://www.facebook.com/adel.rzouga", "Adel Rzouga")
                //new JumpListItem(@"c:\Test1.c4f")
                );

            JumpListCustomCategory catActions2 = new JumpListCustomCategory("Supervised by :");
            catActions2.AddJumpListItems(

                new JumpListLink("http://www.facebook.com/Ahmedayadiesprit", "Ahmed Ayadi")
                );


            jumplist.AddCustomCategories(catActions, catActions2);
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            string systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);

            //IJumpListTask notepadTask = new JumpListLink(System.IO.Path.Combine(systemFolder, "notepad.exe"), "Open Notepad")
            //{
                //IconReference = new IconReference(Path.Combine(systemFolder, "notepad.exe"), 0)
            //};
            //jumplist.AddUserTasks(notepadTask, new JumpListSeparator());


            //Tache propre a l'application
            //jumplist.AddUserTasks(new JumpListLink(System.IO.Path.Combine(Environment.CurrentDirectory, "test.exe"), "Disponible"){ wodXMPP1.SetStatus(WODXMPPCOMLib.StatusEnum.Chat, null) });
            //jumplist.AddUserTasks(new JumpListLink(Path.Combine(Environment.CurrentDirectory, "test.exe"), "Occupé") { Arguments = "Occupé" });
            //jumplist.AddUserTasks(new JumpListLink(Path.Combine(Environment.CurrentDirectory, "test.exe"), "Absent") { Arguments = "Absent" });
            //jumplist.AddUserTasks(new JumpListLink(Path.Combine(Environment.CurrentDirectory, "test.exe"), "Hors Ligne") { Arguments = "Hors Ligne" });
            //Ajout d'une nouvelle Cathegorie
            //JumpListCustomCategory category = new JumpListCustomCategory("Mail");
            //category.AddJumpListItems(new JumpListLink(Path.Combine(Environment.CurrentDirectory, "MiMail.exe"), "New Message") { Arguments = "newMessage" });
            //jumplist.AddCustomCategories(category);

            



            //JumpListLink dispo = new JumpListLink("", "Disponible");
            //JumpListLink occpe = new JumpListLink("", "Occupé");
            //JumpListLink absent = new JumpListLink("", "Absent");
            //JumpListLink hl = new JumpListLink("", "Hors Ligne");
            //dispo.IconReference = new IconReference("cmd.exe", 0);
            //dispo.IconReference = new IconReference(Path.Combine("C:\\Users\\Nizar\\Documents\\Visual Studio 2008\\Projects\\WpfApplication16\\WpfApplication16\\Resources", "About.ico"), 0);
            //dispo.IconReference = new IconReference(Assembly.GetEntryAssembly().Location, 0);
            //jumplist.AddUserTasks(dispo,occpe,absent,hl);


            




            ////Raffrechissement de la JumpListe////
            jumplist.Refresh();
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }


        void goToEsprit(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.esprit-tn.com");
        }

         void goToMoodle(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.esprit-moodle.com");
        }

        void goToEsprit_ens(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.esprit.ens.tn/fr/index.htm");
        }

        
        /*
        private void button2_Click(object sender, RoutedEventArgs e)

        {
            TaskbarManager.Instance.SetOverlayIcon(new WindowInteropHelper(this).Handle,Properties.Resources.About, "IveGotMail");
            
        }
        */
        




        /*
         *
        
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error);
            TaskbarManager.Instance.SetProgressValue(100, 100);
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Paused);
            TaskbarManager.Instance.SetProgressValue(100, 100);
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
            TaskbarManager.Instance.SetProgressValue(100, 100);
        }

        

        */



        void wodXMPP1_Disconnected(int ErrorCode, string ErrorText)
        {
            WarningBox warningBox = new WarningBox();
            warningBox.Owner = Window.GetWindow(this);
            warningBox.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            warningBox.text.Text = ErrorText;
            warningBox.ShowDialog();
            Connexion cn = new Connexion();
            cn.Show();
            this.Close();
        }

        /// Fin - End ///

       }
    }


        


    

